/**
 * @Author:卿雨欣
 * @Date:2020/7/3
 * @Description:这是产品买入页面的金额输入框以及成分产品购买明细
 */
import React,{Component} from "react";
import "../../../access/images/success.png"
import {InputItem, List, Toast, WhiteSpace, Modal, Checkbox,Button, Radio, ActionSheet, Result} from 'antd-mobile';
import axios from "axios";
import {getCookieId, getCookieRisk} from "../../Login/Component_Login/GetCookie";
const isIPhone = new RegExp('\\biPhone\\b|\\biPod\\b', 'i').test(window.navigator.userAgent);
let moneyKeyboardWrapProps;
let wrapProps;
var ss = false;
const AgreeItem = Checkbox.AgreeItem;
if (isIPhone) {
    moneyKeyboardWrapProps = {
        onTouchStart: e => e.preventDefault(),
    };
    wrapProps = {
        onTouchStart: e => e.preventDefault(),
    };
}
const Item = List.Item;
const alert = Modal.alert; //购买明细弹窗
const prompt = Modal.prompt;
export default class FormBuyIn extends Component{
    constructor(props) {
        super(props);
        this.state={
            inputMoney:0,
            redBoolen:false,//判断待支付金额什么时候变为红色
            combinatiobShares:[],//组合的成分产品列表
            trialCalculationList:[],//成分产品试算金额列表
            trial:false,//false展示初始的成分产品列表，true展示试算金额列表
            checkedR:false,//协议单选框的选中状态
            test:true,
            validateMoney:false,
            validateAccount:false,
            checkRiskLevel:false,
            validatePassword:false,
            realTotalAmount:0,
            merchandiseAmount:0,
        }
        this.validateAccount.bind(this);
        this.validatePassword.bind(this);
        this.validateMoney.bind(this);
        this.buyIn.bind(this);
        this.radioOnChange.bind(this);
        this.continueBuy.bind(this);
        this.checkRiskLevel.bind(this);
        this.showActionSheet.bind(this);
    }
    //获取页面数据，成分产品
    componentWillMount() {
        axios({
            method:"GET",
            url:"http://39.101.141.248:9527/combinationShare/getCombinationShareInfo",
            params:{comBaseId:this.props.comBaseId},
        }).then(res=>{
            if(res.data.code === 200){
                this.setState({
                    combinatiobShares:res.data.combinatiobShares
                })
            }
        }).catch(error=>{
            console.log(error);
        });
    }
    //
    //成分产品购买试算以及验证输入金额是否满足起购金额
    validateMoney = (rule, value, callback) => {
        //满足起购金额，进行金额试算'
        if (value && value>=(this.props.conBaseStartMoney*10000)) {
            callback();
            axios({
                method:"GET",
                url:"http://39.101.141.248:9527/transaction/trialCalculation",
                params:{
                    comBaseId:this.props.comBaseId,
                    amount:value,
                },
            }).then(res=>{
                if(res.data.code === 200){
                    var real = res.data.realTotalAmount;
                 /*   localStorage.setItem("inputMoney",real);
                    localStorage.setItem("redBoolen",true);*/
                    this.setState({
                        inputMoney:value,
                        redBoolen:true,
                        merchandiseAmount:res.data.realTotalAmount,
                        trial:true,
                        trialCalculationList:res.data.trialCalculationList,
                        /*realTotalAmount:res.data.realTotalAmount*/
                    })
                }
            }).catch(error=>{
                console.log(error);
            });
        } else { //不满足起购金额，提示错误
           /* Toast.info("购买金额不得低于100,00万元")  一键买入组合时，您的购买金额会自动根据管理人的持仓配比和在途交易调整至最合适的配比。*/
            callback(new Error('At least four characters for account'));
          /*  localStorage.setItem("redBoolen",false);*/
            this.setState({
                inputMoney:0.00,
                redBoolen:false,
                trial:false,
            })
        }
    }
    //验证账户余额是否充足
    validateAccount(userId,password){
        var accountFlag = false;
        axios({
            method:"GET",
            url:"http://39.101.141.248:9527/transaction/verifyAccountAmount",
            params:{
                userId:userId,
               amount:this.state.inputMoney,
            },
        }).then(res=>{
            if(res.data.code === 200){
                accountFlag = true;
                this.buyIn(userId,password)
            }
            else if(res.data.code === 201){
                accountFlag = false;
                alert(
                    "余额不足",
                    "账户余额不足，请充值之后进行购买",
                    [
                        {text:'确定',onPress:()=>console.log("余额不足弹窗确定")},
                    ])
            }
            else if(res.data.code === 501){
                console.log("账户不存在")
                accountFlag = false;
            }
        }).catch(error=>{
            console.log(error);
        });
        this.setState({
            validateAccount:accountFlag,
        })
        return accountFlag;
    }
    //保存协议，风险承担结果
    agreeRecord(protocolId){
        axios({
            method:"GET",
            url:"http://39.101.141.248:9527/protocol/protocolRecord",
            params:{
                comBaseId:this.props.comBaseId,
                protocolId:protocolId,
                userId:getCookieId(),
            },
        }).then(res=>{
        }).catch(error=>{
            console.log(error);
        });
    }
    //下单购买，交易密码验证正确之后
    buyIn(userId,userPassword){
        //验证输入金额是否满足条件
        axios({
            method:"GET",
            url:"http://39.101.141.248:9527/transaction/merchandise",
            params:{
                userId:userId,
                comBaseId:this.props.comBaseId,
                amount:this.state.inputMoney,
                merchandiseAmount:this.state.merchandiseAmount,
            },
        }).then(res=>{
            var data =res.data;
            if(res.data.code === 200) {
                this.agreeRecord(2);
                this.agreeRecord(1);
                var path = {
                    pathname:'/buyResult',
                    query:data,
                }
                alert(
                    "支付成功",
                    (
                        <Result
                            img= {<img src={require("../../../access/images/success.png")} style={{width:100,height:100,textAlign:"center",marginLeft:-10,marginTop:-30,marginBottom:200}}/>}
                        />
                    ),
                    [
                        {text:'确定',onPress:()=>this.props.history.push(path)},
                    ])
            }
        }).catch(error=>{
            console.log(error);
        });
    }
    //验证交易密码是否正确
    validatePassword(userId,userPassword){
        axios({
            method:"GET",
            url:"http://39.101.141.248:9527/transaction/verifyPassword",
            params:{
                userId:userId,
                userPassword:userPassword,
            },
        }).then(res=>{
            if(res.data.code === 200){
                this.validateAccount(userId,userPassword);
                this.setState({
                    validatePassword:true,
                })
            }else{
                this.setState({
                    validatePassword:false,
                })
                ss=false
                alert(
                    "密码错误",
                    "交易密码错误，请输入正确的密码",
                    [
                        {text:'忘记密码',onPress:()=>console.log("忘记密码")},
                        {text:'重试',onPress:()=> this.continueBuy(getCookieId())},
                    ])
            }
        }).catch(error=>{
            console.log(error);
        });
        return ss;
    }
    //继续购买函数 用户id:cookie;组合产品id：页面间传值，产品列表-买入（传递一个产品对象，缓存）
    continueBuy(userId){
        prompt(
            '请输入交易密码',
            (
                <div>
                    <p>{this.state.productName}</p>
                    <p style={{fontSize:16,color:"black"}}>{this.state.merchandiseAmount}元</p>
                </div>
            ),
            password => this.validatePassword(getCookieId(),`${password}`)/*this.buyIn(userId,`${password}`)*/,
            'secure-text',
            null,
            ['请输入交易密码'],
        )
    }
    //放弃购买函数
    giveUpBuy(userId,comBaseId){
        console.log("放弃购买函数")
    }
    //验证风险等级是否匹配
    checkRiskLevel(userId,comBaseId){
        var flag = false;
        axios({
            method:"GET",
            url:"http://39.101.141.248:9527/transaction/verifyRiskLevel",
            params:{
                userId:userId,
                comBaseId:comBaseId,
            }
        }).then(res=>{
            if(res.data.code === 200){
                flag = true;
                alert(
                    "风险提示",
                    "该组合与您的风险等级匹配",
                    [
                        {text:'继续购买',onPress:()=>this.continueBuy(getCookieId(),this.props.comBaseId)},
                    ])
            }
            else if(res.data.code === 201){
                flag = false;
                alert(
                    "风险提示",
                    (
                        <div style={{textAlign:"left"}}>
                            <p>{this.props.comBaseName}为({this.props.comBaseRiskLevel})超出您当前风险承受能力({getCookieRisk()})。本机构特此向您书面警示:请您认真了解产品风险特征，审慎决定购买。</p>
                            <p style={{color:"#f8a83f",textAlign:"left"}}>点击继续购头即表明您了解上述提示，并承诺以下内容：</p>
                            <p>本人已充分了解.上述提示内容，已知悉{this.props.comBaseName}等级高于本人风险承受能力，并且已充分了解该产品风险特征。
                                经审慎考虑，本人仍坚持申请购买，并自愿承担可能产生的一切不利后果。贵司及销售人员不存在主动向本人推介该产品的行为。</p>
                        </div>
                    ),
                    [
                        {text:'放弃购买',onPress:()=>this.giveUpBuy(getCookieId(),this.props.comBaseId)},
                        {text:'继续购买',onPress:()=>this.continueBuy(getCookieId(),this.props.comBaseId)},
                    ])
            }
        }).catch(error=>{
            console.log(error);
        });
        this.setState({
            checkRiskLevel:flag,
        })
        return flag;
    }
    //表单提交
    onSubmit = () => {
        this.props.form.validateFields({ force: true }, (error) => {
            if (!error) {
                if(this.state.checkedR === false){
                    alert(
                        "协议同意提示",
                        "请确认本人已阅读相关协议并理解上述内容，并承担风险",
                        [
                            {text:'取消',onPress:()=>console.log('取消协议')},
                            {text:'确定',onPress:()=>{this.setState({checkedR:true})}}
                        ])
                }else{
                    //风险验证
                    this.checkRiskLevel(getCookieId(),this.props.comBaseId);
                }
            } else {
                alert('请输入符合条件的购买金额');
            }
        });
    }
    //表单清空
    onReset = () => {
        this.props.form.resetFields();
    }
    //协议PDF弹窗，下面
    showActionSheet = () => {
        const BUTTONS = ['组合用户服务协议','我知道了'];
        ActionSheet.showActionSheetWithOptions({
                options: BUTTONS,
                cancelButtonIndex: BUTTONS.length - 1,
                // title: 'title',
                maskClosable: true,
                'data-seed': 'logId',
                wrapProps,
            },
            (buttonIndex) => {
                this.setState({ clicked: BUTTONS[buttonIndex] });
                if(buttonIndex !== BUTTONS.length - 1 ){
                    return new Promise((resolve) => {
                        this.props.history.push("/pdfShow")
                        setTimeout(resolve, 1000);
                    });
                }
            });
    }
    //同意协议单选框
    radioOnChange(e){
        var checked = e.target.checked;
        this.setState({
            checkedR:checked,
        })
        return checked;
    }

    render() {
        const { getFieldDecorator,getFieldProps, getFieldError } = this.props.form;
        return(
            <form>
                <List>
                    <InputItem
                        {...getFieldProps('money2', {
                            // 输入小数点后最多两位
                            normalize: (v, prev) => {
                                if (v && !/^(([1-9]\d*)|0)(\.\d{0,3}?)?$/.test(v)) {
                                    if (v === '.') {
                                        return '0.';
                                    }
                                    return prev;
                                }
                                return v;
                            },
                           /* initialValue: this.state.inputMoney?this.state.inputMoney:localStorage.getItem("inputMoney"),*/
                            rules: [
                                { required: true, message: '请输入购买金额！' },
                                { validator: this.validateMoney.bind(this) },
                            ],
                        })}
                        error={!!getFieldError('money2')}
                        onErrorClick={() => {
                            /*alert(getFieldError('money2').join('、'));*/
                            Toast.info("购买金额不得低于起购金额")
                        }}

                        type={'money'}
                        placeholder={this.props.conBaseStartMoney+"0000元起购"}
                        onVirtualKeyboardConfirm={v => console.log(v)/*console.log('onVirtualKeyboardConfirm:', v)*/}
                        clear
                        moneyKeyboardWrapProps={moneyKeyboardWrapProps}
                    >{<span style={{fontSize:28}}>¥</span>}
                    </InputItem>
                </List>
                <WhiteSpace/>
                <div>
                    <List>
                        <Item thumb={require("./../../../access/images/info.png")}
                              onClick={()=>{
                                  alert(
                                      "提示",
                                      " 一键买入组合时，您的购买金额会自动根据管理人的持仓配比和在途交易调整至最合适的配比",
                                      [
                                      {text:'我知道了',onPress:()=>console.log('我知道了')},
                                  ])
                              }}>
                            <span style={{fontSize:14,color:"darkgray"}} >购买明细</span>
                        </Item>
                        {
                            !this.state.trial ?(
                                this.state.combinatiobShares.map((item, index) => {
                                return (
                                    <Item  wrap key={item.proTsCode}>
                                        <div className="font3" style={{float:"left",marginTop:-20,height:40}}>
                                            <p style={{marginTop:10,fontSize:16}}>{item.proName}</p>
                                            <p className="gray-text" style={{textAlign:"left"}}>{item.proTsCode}</p>
                                        </div>
                                        <div className="my-list-item2" >--</div>
                                       {/* {getFieldDecorator('list1')(
                                            <InputItem/>)}*/}
                                    </Item>
                                )
                            })
                            ):null
                        }
                        {
                            this.state.trial?(
                                this.state.trialCalculationList.map((item, index) => {
                                    return (
                                        <Item  wrap key={item.proTsCode}>
                                            <div>
                                                <div className="font3" style={{float:"left",marginTop:-20,height:40}}>
                                                    <p style={{marginTop:10,fontSize:16}}>{item.proName}</p>
                                                    <p className="gray-text" style={{textAlign:"left"}}>{item.proTsCode}</p>
                                                </div>
                                                <div className="font3" style={{float:"right",marginTop:-20,height:40}}>
                                                    <p style={{marginTop:10,fontSize:16}}>{item.amount}</p>
                                                    <p className="gray-text" style={{textAlign:"right"}}>{item.ratio}</p>
                                                </div>
                                            </div>
                                        </Item>
                                    )
                                })
                            ):null
                        }
                    </List>
                    <div style={{width:"100%",height:30}}>
                        <div style={{float:'left',marginTop:-10}}>
                            <AgreeItem ref='test' checked={this.state.checkedR} data-seed="logId"onChange={e => this.radioOnChange(e)}>
                                <span style={{color:"darkgray",fontSize:12}}>我已仔细阅读并同意</span>
                            </AgreeItem>
                        </div>
                        <a style={{color:"#f8a83f",fontSize:12,marginTop:-50}} onClick={this.showActionSheet}>《组合用户服务协议》</a>
                    </div>
                    <div style={{position:"fixed",bottom:0,backgroundColor:"white",width:"100%",height:40}}>
                        <div style={{float:"left",textAlign:"center"}}>
                            <span style={{color:"#666666",marginLeft:20,marginRight:5,lineHeight:3,textAlign:"center"}}>待支付</span>
                            <span className={this.state.redBoolen? 'redBoolen' : ''} >{this.state.merchandiseAmount}元</span>
                        </div>
                        <div onClick={this.onSubmit}  className={this.state.redBoolen ? 'buyIn-okButton-yes' : 'buyIn-okButton-no'} >
                            确定
                        </div>
                    </div>
                </div>
            </form>
        )
    }
}